from utlis.smscode import sms_code
import re
from qiniu import Auth, put_file, etag
import qiniu.config
from utlis.CORS import BaseHandler
from myredis import r
from utlis.my_jwt import jj
from utlis.mysql import db
#开启debug模式
settings = {'debug' : True}
# 用户协议
class Userxieyi(BaseHandler):
    def get(self):
        name=self.get_query_argument("name")
        sql=f"""select * from user_agreement where name="{name}";"""
        res=db.findone(sql)
        self.finish({"code":200,'msg':res})
import json
# 导入雪花算法
import snowflake.client
#封装雪花算法
def create_ordercode(tablename,count):
    #生成唯一id
    code = snowflake.client.get_guid()
    # 使用redis进行回拨
    value = r.get_str(tablename)
    if value:
        if int(code) < int(value):
            create_ordercode(tablename,count)
    #如果redis中没有，就进行存储
    r.set_str(tablename,code)
    # 取模块到列表里
    print('hash(code)',hash(code))
    number = hash(code) % count
    if number == 0:
        return tablename,code
    else:
        return tablename + str(number),code




# 贷款的接口
class borrow_money(BaseHandler):
    def post(self):
        res=self.request.body
        data=json.loads(res)
        print(data,"data>>>>>>>>>>>>")
        # 加入标的表
        tablename,code=create_ordercode("landmarks",3)
        print(tablename,"tablename")
        print(code,"code")
        sql=f"""insert into {tablename} (code,userid, descrip,tmoney,term,interest_rate) values ({code},{int(data['userid'])},"{data['describe']}",{data['money']},{int(data['term'])},0.03);"""
        print("sql>>>",sql)
        db.add(sql)
        db.commit()
        print(code)
        r.list_push("weishenhe",code)
        print(res)
        self.finish({"code":200,'msg':'添加成功'})




# 获取当前角色审核的内容：
class getaudit(BaseHandler):
    def get(self):
        userid=self.get_query_argument("userid")
        page=self.get_query_argument("page")
        page_size=self.get_query_argument("page_size")
        start=(int(page)-1)*int(page_size)
        userid=int(userid)
        sql=f"""select code,descrip,tmoney,term,status from landmarks where audit_userid={userid} union all select code,descrip,tmoney,term,status from landmarks1 where audit_userid={userid} union all select code,descrip,tmoney,term,status from landmarks2 where audit_userid={userid} limit {start},{page_size};"""
        res=db.findAll(sql)
        for i in res:
            i['code']=str(i['code'])

        sql2="""select count(*) from (select code from landmarks where audit_userid=7 union all select code from landmarks1 where audit_userid=7 union all select code from landmarks2 where audit_userid=7) as t;"""
        ress=db.findone(sql2)
        total=int(ress['count(*)'])
        self.finish({"code":200,'msg':res,'total':total})
# 进行审核管理
import time
import datetime
# 审核接口
class audit(BaseHandler):
    def get(self):
        code=self.get_query_argument("code")
        status=self.get_query_argument("status")
        table="landmarks"
        code=int(code)
        number = hash(code) % 3
        rr=datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        if number > 0:
            table = table + str(number)
            sqll = f"""update {table} set status={int(status)},audit_time="{rr}" where code={code};"""
            print('sql>>>',sqll)
            db.add(sqll)
            db.commit()
            r.sortedset_add()

            self.finish({"code":200,'msg':'审核成功'})
        if number == 0:
            table = "landmarks"
            sqll = f"""update {table} set status={int(status)} ,audit_time="{rr}" where code={code};"""
            db.add(sqll)
            print('sql>>>', sqll)
            db.commit()
            self.finish({"code": 200, 'msg': '审核成功'})

# 调用支付宝沙箱接口
# 导包
import random
from utlis.comm import get_ali_object
class ailpay_jie(BaseHandler):
    def get(self):
        pay=get_ali_object()
        query_params=pay.direct_pay(
            subject="坑你钱的", # 商品描述
            out_trade_no=str(random.randint(10000,99999)),# 用户购买的商品订单号，每次不一样
            total_amount=float(100.100)
        )
        pay_url="https://openapi.alipaydev.com/gateway.do?{0}".format(query_params) # 支付宝网关地址
        self.write({"code":200,'msg':pay_url})

# 充值接口
class top_up_jie(BaseHandler):
    def get(self):
        userid=self.get_query_argument("userid")
        if userid==None:
            self.finish({"code":400,'msg':'请先登录'})
            return
        sql1=f"""select * from open_bank where userid={userid};"""
        res=db.findone(sql1)
        self.finish({"code":200,'bank_code':res['code'][-4:]})
    def post(self):
        can=self.request.body
        data=json.loads(can)
        tmoney=data['tmoney']
        password=data['password']
        userid=data['userid']
        if not all([tmoney,password,userid]):
            self.finish({"code":400,'msg':'字段不完整'})
            return
        sql1 = f"""select * from open_bank where userid={userid};"""
        res = db.findone(sql1)
        if password!=res['pay_password']:
            self.finish({"code":400,'msg':'密码不正确'})
        try:
            tmoney=int(tmoney)
            tim=time.time()
            red=random.randint(10000000000000000,99999999999999999)
            pay=get_ali_object()
            query_params=pay.direct_pay(
                subject="账户充值", # 商品描述
                out_trade_no=str(red),# 用户购买的商品订单号，每次不一样
                total_amount=float(tmoney)
            )
            pay_url="https://openapi.alipaydev.com/gateway.do?{0}".format(query_params) # 支付宝网关地址
            sqll=f"""insert into order_form (ddorder,userid,toptime,money) values ("{str(red)}","{userid}","{tim}",{tmoney})"""
            db.add(sqll)
            db.commit()

            times=int(time.time())+1800
            r.sortedset_add('yanshiduilie',red,times)

            # 存入列表
            self.write({"code":200,'msg':pay_url})
        except:
            self.finish({"code":400,'msg':'请输入正确的金额'})

# 支付宝回调接口
class callback(BaseHandler):
    def get(self):
        print("通了>>>>>>>>>>>>>>")
        # 获取返回参数
        data=self.request.arguments
        # 对参数进行处理
        data={k:v[0].decode() for k,v in data.items()}
        # 从字典中把sign删除
        sign=data.pop("sign")
        # 获取支付宝对象
        alipay=get_ali_object()
        # 调用验签
        flag = alipay.verify(data,sign)
        if flag==True:
            try:
                ddcode=data['out_trade_no']
                money=data['total_amount']
                sql=f"""select * from order_form where ddorder={ddcode}"""
                res=db.findone(sql)
                sqlu=f"""update order_form set state='已完成' where id={res['id']}"""
                sqll=f"""select * from p2p.user where id={res['userid']}"""
                res2=db.findone(sqll)
                sql2=f"""insert into top_up (ddorder, userid, toptime, money,state) values ("{ddcode}",{res['userid']},"{time.time()}",{money},"已到账");"""
                money2=float(res2['money'])+float(money)
                sql3=f"""update user set money={money2} where id={res['userid']}; """
                db.update1(sql2)
                db.update1(sql3)
                db.update1(sqlu)
                db.commit()
            # 从redis列表取出
                self.redirect("http://localhost:8080/ok")
            except:
                print("报错了")
                db.rollback()

# 按钮配置
class pbutton(BaseHandler):
    def get(self):
        sql="""select * from  pageresource;"""
        res=db.findAll(sql)
        sq2="""select * from p2p.resource where pid!=0"""
        res2=db.findAll(sq2)
        list=[]
        for i in res2:
            list.append({
                'id':i['id'],
                'name':i['name']
            })
        self.finish({"code":200,'msg1':res,'msg2':list})
    def post(self):
        postlist=self.request.body
        date=json.loads(postlist)
        print("data>>>",date)
        resourceid=date['resourceid']
        userid=date['userid']
        list=date['list']
        for i in list:
            sql=f"""insert into role_resource(userid,resourceid,pageresourceid)values({int(userid)},{resourceid},{i})"""
            db.add(sql)
            db.commit()
            print('sql>>>>',sql)
        self.finish({"code":200,'msg':'配置成功'})

# 获取按钮内容
class getbutton(BaseHandler):
    def get(self):
        url=self.get_query_argument("url")
        try:
            sql=f""" select * from resource where url='{url}';"""
            res=db.findone(sql)
            sq2=f"""select * from role_resource where  resourceid={res['id']};"""
            res2=db.findAll(sq2)
            list=[]
            for i in res2:
                list.append(i['pageresourceid'])
            print('res2>>>>',list)
            list.remove(None)
            list2=[]
            for i in list:
                sq3=f"""select * from pageresource where id={i}"""
                ress=db.findAll(sq3)
                list2.append(ress[0])
            print('list2>>>',list2)
            self.finish({"code":200,'msg':list2})
        except:
            pass

# 投资
class investment(BaseHandler):
    def get(self):
        page = self.get_query_argument("page")
        page_size = self.get_query_argument("page_size")
        key = "landmarks" + str(page)
        print("else")
        start = (int(page) - 1) * int(page_size)

        sqls = "select *  from (select * from landmarks where status=2 union all select * from landmarks1 where status=2 union all select * from landmarks2 where status=2) as t limit %d,%d"%(int(start),int(page_size))
        print(sqls)
        list = db.findAll(sqls)
        print("lst",list)
        lst = []
        for i in list:
            i["interest_rate"] = float(i["interest_rate"])
            i['code']=str(i['code'])
            i['audit_time'] = datetime.datetime.strftime(i['audit_time'],"%Y-%m-%d %H:%M:%S")
            lst.append(i)
        sql1 = "select count(code) as a  from (select * from landmarks where status=2 union all select * from landmarks1 where status=2 union all select * from landmarks2 where status=2) as t"
        res = db.findone(sql1)
        total = res["a"]
        self.finish({"code": 200,"total":total,"data":lst})
    def post(self):
        rr=self.request.body
        data=json.loads(rr)
        code=data['code']
        userid=data['userid']
        money=data['money']
        money=int(money)
        if not all([code,userid,money]):
            self.finish({"code":400,'msg':"字段不完整"})
            return
        sq22=f"""select * from invest where userid={userid}"""
        aaa=db.findAll(sq22)
        list=[]
        for i in aaa:
            list.append(float(i['money']))
        suo=0
        for i in list:
            suo+=i
        print(">>>>>suo",suo)
        print("查询当前用户的>>>>>>",aaa)
        sql=f"""select * from p2p.user where id={userid};"""
        res=db.findone(sql)
        if float(money)>float(res['money']):
            self.finish({"code":400,'msg':'余额不足'})
            return
        zong=float(res['money'])-float(money)
        print('zong>>>>>',zong)
        table = "landmarks"
        code=int(code)
        number = hash(code) % 3
        if number > 0:
            table = table + str(number)
            sq2=f"""select * from {table};"""
            res2=db.findone(sq2)
            lixi=res2['interest_rate']*int(res2['term'])
            print("利息>>>>",lixi)
            # 拼接总收益
            cmoney=lixi+money
            print("总收益>>>>>",cmoney)
            rr = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            sq4=f"""insert into invest (userid,bdid,money,create_time,accrual,cmoney,status) values ({int(userid)},{code},{float(money)},"{rr}",{lixi},{cmoney},1)"""
            sq5=f"""update user set money={zong} where id={userid}"""
            amoney=float(res2['money'])+money
            sq6=f"update {table} set money={amoney}  where code={code}"
            db.update(sq6)
            db.update(sq4)
            db.update(sq5)
            print('sql6>>>>>>>>', sq6)
            self.finish({"code": 200, 'msg': '出借成功'})
            return
        if number == 0:
            table = "landmarks"
            sq3 = f"""select * from {table};"""
            res3 = db.findone(sq3)
            lixi = res3['interest_rate'] * int(res3['term'])
            # 拼接总收益
            cmoney = lixi + money
            amoney = float(res3['money']) + money
            sq6 = f"update {table} set money={amoney}  where code={code}"
            rr = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            sq4 = f"""insert into invest (userid,bdid,money,create_time,accrual,cmoney,status) values ({int(userid)},{code},{float(money)},"{rr}",{lixi},{cmoney},1)"""
            sq5 = f"""update user set money={zong} where id={userid}"""
            print('sql6>>>>>>>>',sq6)
            db.update(sq6)
            db.update(sq4)
            db.update(sq5)
            self.finish({"code": 200, 'msg': '出借成功'})


class allow(BaseHandler):
    def get(self):
        page = self.get_query_argument("page")
        page_size = self.get_query_argument("page_size")
        key = "landmarks" + str(page)
        print("else")
        start = (int(page) - 1) * int(page_size)

        sqls = "select *  from (select * from landmarks where status=2 and money>tmoney union all select * from landmarks1 where status=2 and money>tmoney union all select * from landmarks2 where status=2 and money>tmoney) as t limit %d,%d"%(int(start),int(page_size))
        print(sqls)
        list = db.findAll(sqls)
        print("lst",list)
        lst = []
        for i in list:
            i["interest_rate"] = float(i["interest_rate"])
            i['code']=str(i['code'])
            i['audit_time'] = datetime.datetime.strftime(i['audit_time'],"%Y-%m-%d %H:%M:%S")
            lst.append(i)
        sql1 = "select count(code) as a  from (select * from landmarks where status=2 and money>tmoney union all select * from landmarks1 where status=2 and money>tmoney union all select * from landmarks2 where status=2 and money>tmoney) as t"
        res = db.findone(sql1)
        total = res["a"]
        self.finish({"code": 200,"total":total,"data":lst})


    def post(self):
        doe=self.request.body
        date=json.loads(doe)
        table = "landmarks"
        code=date['code']
        userid=int(date['userid'])
        sqla=f"""select * from invest where bdid={code}"""
        resa=db.findone(sqla)
        sqlb=f"""select * from user where id={userid}"""
        resb=db.findone(sqlb)
        code = int(code)
        number = hash(code) % 3
        if number > 0:
            table = table + str(number)
            sqla=f"""update {table} set status=4 where code={code}"""
            qian=int(resb['money'])+int(resa['cmoney'])
            sqlc=f"""update user set money = {qian} where id={userid}"""
            db.update(sqla)
            db.update(sqlc)
            self.finish({"code":200,'msg':'ok'})
        if number == 0:
            table = "landmarks"
            sqla = f"""update {table} set status=4 where code={code}"""
            qian = int(resb['money']) + int(resa['cmoney'])
            sqlc = f"""update user set money = {qian} where id={userid}"""
            db.update(sqla)
            db.update(sqlc)
            self.finish({"code": 200, 'msg': 'ok'})


from elasticsearch import Elasticsearch


es=Elasticsearch("http://47.104.108.172:9200/")
class Getb(BaseHandler):
    def get(self):
        key = 'dadada'
        v = r.get_str(key)
        page = self.get_query_argument('page')
        pagesize = self.get_query_argument('pagesize')
        start = (int(page) - 1) * int(pagesize)
        if v:
            v = v.decode()
            sql = "select * from landmarks where code=%d union all select * from landmarks1 where code=%d union all select * from landmarks2 where code=%d limit %d,%d" % (
            int(v), int(v), int(v), int(start), int(pagesize))
            res = db.findAll(sql)
            for i in res:
                es.index(index='landmarks1',doc_type="1", body={
                    'code': i['code'],
                    'descrip': i['descrip'],
                    'purpose': i['purpose'],
                    'tmoney': i['tmoney'],
                    'pay_type': i['pay_type'],
                    'interest_rate': i['interest_rate'],
                    'term': i['term'],
                    'status': i['status'],
                    'audit_userid': i['audit_userid'],
                    'audit_time': i['audit_time'],
                    'money': i['money'],
                })
        else:
            sql = "select * from landmarks where status=3 union all select * from landmarks1 where status=3 union all select * from landmarks2 where status=3 limit %d,%d" % (
            int(start), int(pagesize))
            res = db.findAll(sql)
            for i in res:
                es.index(index='landmarks1', doc_type="1", body={
                    'code': i['code'],
                    'descrip': i['descrip'],
                    'purpose': i['purpose'],
                    'tmoney': i['tmoney'],
                    'pay_type': i['pay_type'],
                    'interest_rate': i['interest_rate'],
                    'term': i['term'],
                    'status': i['status'],
                    'audit_userid': i['audit_userid'],
                    'audit_time': i['audit_time'],
                    'money': i['money'],
                })

import tornado
from tornado import web
from tornado.websocket import WebSocketHandler
# =========================================================================
import time
from myredis import r
conndict={}
class WebsockHandler(tornado.websocket.WebSocketHandler):
    # 跨域支持
    def check_origin(self, origin):
        return True
    #建立连接
    def open(self):
        #获取参数
        id = int(self.get_query_argument("id"))
        print("程序执行中>>>>>>>>哒哒哒")
        #存储链接
        conndict[id]=self

    #接收消息
    def on_message(self,mes):
        print(mes)
        self.write_message(mes)

    def on_close(self):
        pass








class ZZhandler(tornado.web.RequestHandler):
    def get(self):
        while True:
            time.sleep(5)
            id = int(self.get_query_argument("id"))
            shen = r.list_lpop('shen')
            print(shen,'>>>>>>>>>>>>>')
            if shen:
                print(shen)
                # print(res1)
                # print(res2)
                rlist=[]
                shen=shen.decode()
                rlist.append(shen)
                conndict[id].write_message(json.dumps(rlist))

            else:
                conndict[id].write_message("啥也没有")









